package com.zoe.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * @Author Zoe.Zhang
 * @Date: 2021/07/03
 * @Description $description
 */
@WebFilter(filterName = "MyFilter", urlPatterns = "/api/*")
public class MyFilter implements Filter {
    @Override
    public void destroy() {
        System.out.println("filter destroy===========");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("dofilter start");

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        Object user = request.getSession().getAttribute("user");
        if (Objects.equals(null, user)) {
            PrintWriter writer = resp.getWriter();
            writer.println("请先登录！！");
            writer.write("<a href='../index.jsp'>去登录</a>");
            writer.flush();
        } else {
            chain.doFilter(req, resp);
        }
        System.out.println("dofilter end");
    }

    public void init(FilterConfig config) throws ServletException {
        System.out.println("filter init===========");
    }

}
